/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package cn.cdzdjd.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import cn.cdzdjd.config.MiniProgramConfiguration;
import cn.cdzdjd.config.PlatformApi;
import cn.cdzdjd.dto.form.LoginForm;
import cn.cdzdjd.entity.UserSession;
import cn.cdzdjd.service.UserSessionService;
import cn.cdzdjd.util.IpUtils;
import cn.cdzdjd.util.Result;
import cn.cdzdjd.util.TokenUtil;
import cn.cdzdjd.vo.UserSessionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 登录接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/api")
@Api(tags = "登录接口")
public class ApiLoginController {

	@Resource
	private RestTemplate restTemplate;
	@Resource
	private MiniProgramConfiguration miniProgramConfig;
	@Resource
	private UserSessionService userSessionService;
	@Resource
	private PlatformApi platformApi;

	@ApiOperation("小程序code交换sesison_key")
	@PostMapping("/jscode2session")
	public Result<?> code2session(@RequestBody LoginForm form, HttpServletRequest request) {
		UserSessionVo user = platformApi.code2session(form.getCode(), form.getProvider());
		user.setProvider(form.getProvider());
		UserSession userSession = userSessionService.findByOpenid(user.getOpenid());
		if (ObjectUtils.isEmpty(userSession)) {
			UserSession session = new UserSession();
			BeanUtils.copyProperties(user, session);
			session.setIp(IpUtils.getIpAddr(request));
			userSessionService.insert(session);
			// 获取登录token
			String token = TokenUtil.getToken(session.getId() + "");
			return new Result<>().ok(token);
		} else {
			userSession.setSessionKey(user.getSessionKey());
			userSession.setIp(IpUtils.getIpAddr(request));
			userSessionService.update(userSession);
			String token = TokenUtil.getToken(userSession.getId() + "");
			return new Result<>().ok(token);
		}
	}

}